package com.csun.dsms.controller;

import com.csun.dsms.comment.config.properties.CsunProperties;
import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.annotation.CurrentUser;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.domain.*;
import com.csun.dsms.model.dto.ys.YsBindClasses;
import com.csun.dsms.model.dto.ys.YsQueryDto;
import com.csun.dsms.model.dto.ys.YsStudentVo;
import com.csun.dsms.service.*;
import com.csun.dsms.utils.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/ys")
public class YsSchoolController {

    @Resource
    private YsClassesService ysClassesServiceImpl;

    @Resource
    private YsTeacherService ysTeacherServiceImpl;

    @Resource
    private YsStudentService ysStudentServiceImpl;

    @Resource
    private YsSettingService ysSettingServiceImpl;

    @Resource
    private YsSignRecordService ysSignRecordServiceImpl;
    @Resource
    private OSSManageUtil ossManageUtil;
    @Resource
    private CsunProperties csunProperties;

    /*
     * 班级的添加
     * */
    @Authorization
    @RequestMapping(value = "/classAdd",method = RequestMethod.POST)
    public Wrapper classAdd (@RequestBody YsClasses ysClasses){
        if(PublicUtil.isEmpty(ysClasses.getSchool().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学校不为空");
        }
        if(PublicUtil.isEmpty(ysClasses.getNo().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"班级编号不为空");
        }
        ysClasses.setId(null);
        Integer save = ysClassesServiceImpl.addClasses(ysClasses);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }
    /*
     * 班级的删除
     * */
    @Authorization
    @RequestMapping(value = "/classDelete",method = RequestMethod.POST)
    public Wrapper classDelete (@RequestBody YsClasses ysClasses){
        Integer save = ysClassesServiceImpl.deleteClasses(ysClasses.getId());
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/classEdit",method = RequestMethod.POST)
    public Wrapper classEdit (@RequestBody YsClasses ysClasses){
        if(PublicUtil.isEmpty(ysClasses.getSchool().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学校不为空");
        }
        if(PublicUtil.isEmpty(ysClasses.getNo().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"班级编号不为空");
        }
        if(PublicUtil.isEmpty(ysClasses.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"班级Id不为空");
        }
        Integer save = ysClassesServiceImpl.editClasses(ysClasses);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/classQuery",method = RequestMethod.POST)
    public Wrapper classQuery (@RequestBody YsQueryDto ysQueryDto){
        List<YsClasses> classesList = new ArrayList<>();
        if (ysQueryDto.getTeacherId()!=null){
           classesList = ysClassesServiceImpl.queryListByTeacher(ysQueryDto);
        }else{
            classesList = ysClassesServiceImpl.queryListWithPage(ysQueryDto);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,new PageInfo(classesList));
    }


    @Authorization
    @RequestMapping(value = "/studentAdd",method = RequestMethod.POST)
    public Wrapper studentAdd (@RequestBody YsStudent ysStudent){
        if(PublicUtil.isEmpty(ysStudent.getSchool().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学校不为空");
        }
        if(PublicUtil.isEmpty(ysStudent.getPhone().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"家长手机号不为空");
        }
        ysStudent.setId(null);
        Integer save = ysStudentServiceImpl.addStudent(ysStudent);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }
    /*
     * 班级的删除
     * */
    @Authorization
    @RequestMapping(value = "/studentDelete",method = RequestMethod.POST)
    public Wrapper studentDelete (@RequestBody YsStudent ysStudent){
        Integer save = ysStudentServiceImpl.deleteStudentById(ysStudent.getId());
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/studentEdit",method = RequestMethod.POST)
    public Wrapper studentEdit (@RequestBody YsStudent ysStudent){
        if(PublicUtil.isEmpty(ysStudent.getSchool().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学校不为空");
        }
        if(PublicUtil.isEmpty(ysStudent.getPhone().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"家长手机号不为空");
        }
        if(PublicUtil.isEmpty(ysStudent.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学生Id不为空");
        }
        Integer save = ysStudentServiceImpl.editStudent(ysStudent);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/studentQuery",method = RequestMethod.POST)
    public Wrapper studentQuery (@RequestBody YsQueryDto ysQueryDto){
        List<YsStudent> classesList = ysStudentServiceImpl.queryListWithPage(ysQueryDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,new PageInfo(classesList));
    }

    @Authorization
    @RequestMapping(value = "/studentDetail",method = RequestMethod.POST)
    public Wrapper studentDetail (@RequestBody YsStudent ysStudent){
        YsStudentVo studentVo = ysStudentServiceImpl.queryByStudent(ysStudent);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,studentVo);
    }


    @Authorization
    @RequestMapping(value = "/teacherAdd",method = RequestMethod.POST)
    public Wrapper teacherAdd (@RequestBody YsTeacher ysTeacher){
        if(PublicUtil.isEmpty(ysTeacher.getSchool().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学校不为空");
        }
        if(PublicUtil.isEmpty(ysTeacher.getName().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"姓名不为空");
        }
        ysTeacher.setId(null);
        Integer save = ysTeacherServiceImpl.addTeacher(ysTeacher);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }
    /*
     * */
    @Authorization
    @RequestMapping(value = "/teacherDelete",method = RequestMethod.POST)
    public Wrapper teacherDelete (@RequestBody YsTeacher ysTeacher){
        Integer save = ysTeacherServiceImpl.deleteTeacherById(ysTeacher.getId());
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/teacherEdit",method = RequestMethod.POST)
    public Wrapper teacherEdit (@RequestBody YsTeacher ysTeacher){
        if(PublicUtil.isEmpty(ysTeacher.getSchool().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学校不为空");
        }
        if(PublicUtil.isEmpty(ysTeacher.getName().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"姓名不为空");
        }
        if(PublicUtil.isEmpty(ysTeacher.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"教师id不为空");
        }
        Integer save = ysTeacherServiceImpl.editTeacher(ysTeacher);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/teacherQuery",method = RequestMethod.POST)
    public Wrapper teacherQuery (@RequestBody YsQueryDto ysQueryDto){
        List<YsTeacher> teachers = ysTeacherServiceImpl.queryListWithPage(ysQueryDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,new PageInfo(teachers));
    }

    @Authorization
    @RequestMapping(value = "/teacherBind",method = RequestMethod.POST)
    public Wrapper teacherBind (@RequestBody YsBindClasses ysBindClasses){
        int save = ysTeacherServiceImpl.bindTeacherClass(ysBindClasses);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }



    @Authorization
    @RequestMapping(value = "/showSetting",method = RequestMethod.POST)
    public Wrapper showSetting (@RequestBody YsQueryDto ysQueryDto){
        YsSetting ysSetting = ysSettingServiceImpl.queryBySchool(ysQueryDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,ysSetting);
    }

    @Authorization
    @RequestMapping(value = "/saveSetting",method = RequestMethod.POST)
    public Wrapper saveSetting (@RequestBody YsSetting ysSetting){
        int save = ysSettingServiceImpl.updateSetting(ysSetting);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/addRecord",method = RequestMethod.POST)
    public Wrapper teacherAdd (@RequestBody YsSignRecord ysSignRecord){
        if(PublicUtil.isEmpty(ysSignRecord.getDay().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"日期不能为空");
        }
        if(PublicUtil.isEmpty(ysSignRecord.getName().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"签到人姓名不为空");
        }
        if(PublicUtil.isEmpty(ysSignRecord.getClasses().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"班级不为空");
        }
        if(PublicUtil.isEmpty(ysSignRecord.getStudent().trim())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"学生姓名不为空");
        }
        ysSignRecord.setId(null);
        ysSignRecord.setCreatedTime(new Date());
        Integer save = ysSignRecordServiceImpl.addRecord(ysSignRecord);
        if(save<1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE);
    }

    @Authorization
    @RequestMapping(value = "/recordQuery",method = RequestMethod.POST)
    public Wrapper recordQuery (@RequestBody YsQueryDto ysQueryDto){
        List<YsSignRecord> recordList = ysSignRecordServiceImpl.queryListWithPage(ysQueryDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,new PageInfo(recordList));
    }


    /**
     * 资源上传 -- 小程序
     */
    @Authorization
    @RequestMapping(value="/uploadFile",method= RequestMethod.POST,produces="application/json")
    public Wrapper uploadFile(HttpServletResponse response,
                          HttpServletRequest request) throws Throwable {
        /* 获取文件描述参数 */
        String remark = request.getParameter("remark");
        List<DsmsResource> resources = new ArrayList<DsmsResource>();
        /* 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）*/
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        /* 检查form中是否有enctype="multipart/form-data" */
        if(multipartResolver.isMultipart(request)) {
            /* 将request变成多部分request */
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

            /* 获取multiRequest 中所有的文件名*/
            Iterator iter = multiRequest.getFileNames();
            String timedate  = DateUtil.getOrderNum();	// 时间戳,避免文件覆盖

            while(iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if(file != null) {
                    /* 文件属性获取 */
                    SourceType sourceType = MimeTypeUtil.getSourceType(file.getContentType());
                    /* MultipartFile 转 File */
                    File f=File.createTempFile("tmp", null);
                    file.transferTo(f);
                    f.deleteOnExit();
                    /* OSS文件上传 */
                    ossManageUtil.uploadFile(f, file.getOriginalFilename(), file.getContentType(), sourceType
                            .getSourceTypePath() + "/" + timedate);
                    /* 保存上传的文件属性 */
                    DsmsResource r = new DsmsResource();
                    r.setResourceName(file.getOriginalFilename());
                    r.setResourcePath(csunProperties.getAliyun().getOss().getAccessUrl() + "/"
                            + sourceType.getSourceTypePath() + "/" + timedate + "/" + file.getOriginalFilename());
                    if (StringUtils.isNotBlank(remark)) {
                        r.setRemark(remark);
                    }
                    r.setResourceTypeId(Integer.parseInt(sourceType.getSourceTypeId()));
                    resources.add(r);
                }
            }
        }

        return WrapMapper.ok(resources);
    }

}
